package com.distribute.application.api.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.distribute.application.api.utils.Arith;
import com.distribute.application.api.utils.DateUtils;
import com.distribute.application.api.utils.mobile.MobileCodeUtil;
import com.distribute.framework.model.Account;
import com.distribute.framework.model.Agent;
import com.distribute.framework.model.BindingDistributor;
import com.distribute.framework.model.BrandAccount;
import com.distribute.framework.model.Configur;
import com.distribute.framework.model.Coupon;
import com.distribute.framework.model.DirectOrder;
import com.distribute.framework.model.Distributor;
import com.distribute.framework.model.DistributorIncome;
import com.distribute.framework.model.IncomeRecord;
import com.distribute.framework.model.Member;
import com.distribute.framework.model.OrderDetails;
import com.distribute.framework.model.Parameter;
import com.distribute.framework.model.Product;
import com.distribute.framework.model.RedPacket;
import com.distribute.framework.model.Region;
import com.distribute.framework.model.TbJxsh;
import com.distribute.framework.model.TbJxshIncome;
import com.distribute.framework.model.TbMsg;
import com.distribute.framework.model.TbOrderInvoies;
import com.distribute.framework.model.TbPartnerIncome;
import com.distribute.framework.model.TbPartners;


@Component
public class SqlTask{
	/**
	 * 30分钟取消未支付订单
	 * 
	 */
	@Scheduled(initialDelay = 1000,fixedDelay=300000)
    public void cancelOrder(){
		List<DirectOrder> orders=DirectOrder.where.orderType((short)1).paysStatus((short)0).list(100000);
		if (orders.size()>0) {
			for (DirectOrder order : orders) {
				if (new Date().getTime()-order.getAddTime().getTime()>3600000) {
					DirectOrder.where.id(order.getId()).definex("pays_status < 1").set.status((short)7).update();
				}
			}
		}
	}
	/**
	 * 30发送一次配送待接单短信
	 * 
	 */
	@Scheduled(initialDelay = 1000,fixedDelay=43200000)
    public void cancelPSDJDOrder(){
		List<BindingDistributor> bindingDistributors=BindingDistributor.where.bindingState((short)1).list(10000);
		if (bindingDistributors.size()>0) {
			for (BindingDistributor bindingDistributor : bindingDistributors) {
				Long  counts=DirectOrder.where.distributor(bindingDistributor.getDistributor()).sType((short)1).paysStatus((short)1).status((short)2).count();
				if (counts>0) {
					MobileCodeUtil.sendTextDistributor(bindingDistributor.get$distributor().getMobile(), counts);
				}
			}
			
		}
		
	}
	//查看优惠卷是否过期
	@Scheduled(initialDelay = 1000,fixedDelay=60000)
    public void cancelCoupon(){
		List<Coupon> coupons=Coupon.where.list(1000000);
		for (Coupon coupon : coupons) {
			if (coupon.getDayRemain().getTime()<=new Date().getTime()) {
				coupon.setIsOk((short)1);
				//coupon.setStatus((short)-1);
				coupon.update();
			}
		}
	}
	
	@Scheduled(initialDelay = 1000,fixedDelay=60000)
    public void updateSupportRank(){
		List<DirectOrder> directOrders=DirectOrder.where.status((short)3).list(100000);
		for (DirectOrder order : directOrders) {
				if (order.getGetOrderTime()!=null) {
					if (DateUtils.towDateDays(new Date(), order.getGetOrderTime())>=7) {
						order.setStatus((short)4);
						order.update();
						Member member=Member.where.uid(order.getMember()).get();
						List<IncomeRecord> incomeRecords=IncomeRecord.where.orderNumber(order.getNo()).list(100);
						for (IncomeRecord incomeRecord : incomeRecords) {
							if (incomeRecord.getEndStatus()==(short)1) {
									Account tAccount=Account.where.member(incomeRecord.getBeneficiary()).get();
									if (tAccount!=null) {
										tAccount.setMoney(Arith.round(Arith.add(tAccount.getMoney(), incomeRecord.getIncome()), 2));//直接代理奖励
										 tAccount.update();
										 incomeRecord.setEndStatus((short)2);
										 incomeRecord.update();
										 TbMsg msg=new TbMsg(
												 incomeRecord.getBeneficiary()//会员
													 	,"您获得收益:"+incomeRecord.getIncome()//内容
													 	,new Date()//时间
														);
												msg.save();
									}
							}
						}
						 Parameter parameter=Parameter.where.merchant(order.getMerchant()).get();
						 Configur configur=Configur.where.status((short)1).get();
						 TbOrderInvoies orderInvoies=new TbOrderInvoies(
								    order.getNo()//订单编号
								 	,order.getOrderType()//来源
								 	,order.getMerchant()//品牌商
								 	,order.getMember()//购买人
								 	,order.getTotalSum()//订单总金额
								 	,order.getActualPay()//实际支付金额
								 	,order.getProductFree()//余额抵扣金额
								 	,order.getCouponFree()//优惠卷抵扣金额
								 	,Arith.round(Arith.mul(Arith.sub(order.getTotalSum(), order.getDispatFee()), configur.getProfitRatio()), 2)//平台收益
								 	,0.0//普通间接收益
								 	,0.0//普通直接收益
								 	,0.0//代理间接收益
								 	,0.0//代理直接收益
								 	,0.0//合伙人收益
								 	,0.0//配送商收益
								 	,0.0//经销商收益
								 	,0.0
								 	,new Date()//添加时间
								 );
						    orderInvoies=orderInvoies.save();
						    if (member.gettTop()!=null&&!member.gettTop().equals("")) {
						    	Agent agent=Agent.where.member(Long.parseLong(member.gettTop())).merchant(order.getMerchant()).get();
						    	if (agent!=null) {
						    		orderInvoies.setTboiDlZj(Arith.round(Arith.mul(Arith.sub(order.getActualPay(), order.getDispatFee()), parameter.getpDlZj()), 2));
								}else {
									orderInvoies.setTboiPtZj(Arith.round(Arith.mul(Arith.sub(order.getActualPay(), order.getDispatFee()), parameter.getpPtZj()), 2));
								}
							}
						    if (member.gettToptop()!=null&&!member.gettToptop().equals("")) {
						    	Agent agent=Agent.where.member(Long.parseLong(member.gettToptop())).merchant(order.getMerchant()).get();
						    	if (agent!=null) {
						    		orderInvoies.setTboiDlJj(Arith.round(Arith.mul(Arith.sub(order.getActualPay(), order.getDispatFee()), parameter.getpDlJj()), 2));
								}else {
									orderInvoies.setTboiPtJj(Arith.round(Arith.mul(Arith.sub(order.getActualPay(), order.getDispatFee()), parameter.getpPtJj()), 2));
								}
							}
						    if (order.getDistributor()!=null) {
						    	Distributor distributor=Distributor.where.id(order.getDistributor()).get();
						    	if (distributor!=null) {
						    		DistributorIncome distributorIncome=DistributorIncome.where.directOrder(order.getId()).distributor(distributor.getId()).get();
						    		if (distributorIncome!=null&&distributorIncome.getOrderStatus()==(short)1) {
										orderInvoies.setTboiPsSy(Arith.round(Arith.mul(Arith.sub(order.getTotalSum(), order.getDispatFee()), parameter.getpPsYj()), 2));
													 Account tAccount=Account.where.member(distributor.getMember()).get();
													 if (tAccount!=null) {
														 tAccount.setMoney(Arith.round(Arith.add(tAccount.getMoney(), distributorIncome.getDistriIncome()), 2));//直接代理奖励
														 tAccount.update();
														 distributorIncome.setOrderStatus((short)2);
														 distributorIncome.update();
														 TbMsg msg=new TbMsg(
																 distributor.getMember()//会员
																	 	,"您获得收益:"+distributorIncome.getDistriIncome()//内容
																	 	,new Date()//时间
																		);
																msg.save();
													}
													
										}
						    	  	
						    		BindingDistributor bindingDistributor=BindingDistributor.where.merchant(order.getMerchant()).distributor(distributor.getId()).get();
									if (bindingDistributor!=null&&bindingDistributor.getBindingdJxsh()!=null) {
										TbJxsh jxs=TbJxsh.where.tbjId(bindingDistributor.getBindingdJxsh()).get();
										if (jxs!=null) {
											order.setJxs(jxs.getTbjName());
											order.update();
										}
										orderInvoies.setTboiJxsSy(((Arith.paytype(order.getTotalSum(), order.getDispatFee(), order.getDx(), parameter.getpPsYj(),order.getCouponFree()))*0.08)/0.18);
										 List<OrderDetails> orderDetails=OrderDetails.where.orders(order.getId()).list(-1);
										 List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
											for (OrderDetails orderDetails2 : orderDetails) {
												Map<String, Object> map=new HashMap<String, Object>();
												map.put("goodsNumber",orderDetails2.getGoodsNumber());
												map.put("name", orderDetails2.getName());
												map.put("price", orderDetails2.getPrice());
												map.put("number", orderDetails2.getNumber());
												map.put("status", orderDetails2.getStatus$());
												list.add(map);
											}	
										TbJxshIncome jxshIncome=new TbJxshIncome(
												order.getMerchant()
												,bindingDistributor.getBindingdJxsh()//经销商
												,order.getJxs()
											 	,order.getId()//订单编号
											 	,order.getAddTime()
												,order.getConsigneeName()
												,order.getDistributor$()
												,order.getOrderType()
												,JSON.toJSONString(list)
											 	,((Arith.paytype(order.getTotalSum(), order.getDispatFee(), order.getDx(), parameter.getpPsYj(),order.getCouponFree()))*0.08)/0.18//收益金额
											 	,new Date()
												);
										jxshIncome.save();
									}
						    	}
							}
						 TbPartners partners=TbPartners.where.tbpJiedao(order.getStreet()).get();
						 Region region=Region.where.id(order.getStreet()).get();
						 if (partners!=null) {
							 Member member2=Member.where.uid(partners.getTbpMember()).get();
							 orderInvoies.setTboiHhrSy(Arith.round(Arith.mul(Arith.sub(order.getTotalSum(), order.getDispatFee()), parameter.getpHhrYj()), 2));
							 TbPartnerIncome partnerIncome=new TbPartnerIncome(
									     order.getMerchant()//品牌
									 	,member2.getUid()//会员
									 	,order.getNo()
									 	,order.getOrderType()
									 	,member2.getNickName()
									 	,member.getHeader()//头像
									 	,member.getNickName()//昵称
									 	,region.getName()//街道
									 	,region.get$parent().getFullName()
									 	,new Date()//下单时间
									 	,Arith.round(Arith.mul(Arith.sub(order.getTotalSum(), order.getDispatFee()), parameter.getpHhrYj()), 2)//收益金额
									 );
							 partnerIncome.save();
						}
						 orderInvoies.setTboiSySy(Arith.round(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(
								                                                         order.getTotalSum(), order.getDispatFee()),
								                                                         orderInvoies.getTboiPtSy()),
																						 orderInvoies.getTboiPtJj()),
																						 orderInvoies.getTboiPtZj()),
																						 orderInvoies.getTboiDlJj()),
																						 orderInvoies.getTboiDlZj()),
																						 orderInvoies.getTboiPsSy()),
																						 orderInvoies.getTboiHhrSy()),
																						 orderInvoies.getTboiJxsSy()), 2));
						orderInvoies.update(); 
						BrandAccount brandAccount=BrandAccount.where.brand(order.getMerchant()).get();
						if (brandAccount==null) {
							BrandAccount bccount=new BrandAccount(
									order.getMerchant()//所属品牌 [非空]
								 	,orderInvoies.getTboiSySy()//总金额
								 	,orderInvoies.getTboiSySy()//累计收益
								 	,0.0//累计提现
								 	,new Date()//修改时间 [非空]
								 	,new Date()//添加时间 [非空]
								 	,(short)1//状态 [非空]
									);
							bccount.save();
						}else {
							brandAccount.setMoney(Arith.round(Arith.add(brandAccount.getMoney(), orderInvoies.getTboiSySy()), 2));
							brandAccount.setlSmoney(Arith.round(Arith.add(brandAccount.getlSmoney(), orderInvoies.getTboiSySy()), 2));
							brandAccount.update();
						}
					}
				}else {
					order.setGetOrderTime(new Date());
					order.update();
				}
		}
		List<RedPacket> redPackets=RedPacket.where.status((short)1).list(10000000);
          		for (RedPacket redPacket : redPackets) {
					if (new Date().getTime()>=redPacket.getValidity().getTime()) {
						if (redPacket.getQuantity()>0) {
							Product product=Product.where.id(redPacket.getProduct()).get();
							product.setNumber(product.getNumber()+redPacket.getQuantity());
							product.update();
							redPacket.setQuantity(0);
							redPacket.setStatus((short)0);
							redPacket.update();
						}
					}
				}
	}

}